﻿// Apache-2.0 License
// Copyright (c) 2021-2022 朱飞龙
// 电话/微信：18706708563  QQ群：136192142

using Admin.NET.Application.Util.Extension;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Radius.NET.Interface.Kingdee.Entity;

namespace Radius.NET.Interface.Kingdee.BasicInfoModule;

/// <summary>
/// 基础资料服务
/// </summary>
[ApiDescriptionSettings(KingdeeConfigConst.GroupName, Order = 002)]
public class InventoryService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Inventory> _inventoryRepository;
    private readonly KingdeeUtil _kingdeeUtil;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="inventoryRepository"></param>
    /// <param name="kingdeeUtil"></param>
    public InventoryService(SqlSugarRepository<Inventory> inventoryRepository,
        KingdeeUtil kingdeeUtil)
    {
        _inventoryRepository = inventoryRepository;
        _kingdeeUtil = kingdeeUtil;
    }

    #region 同步金蝶云星空物料档案到本地
    /// <summary>
    /// 同步金蝶云星空物料档案到本地
    /// </summary>
    /// <returns></returns>
    [HttpPost("/kindeeIcloud/basicinfo/inventorylist/{cid}"), AllowAnonymous]
    public async Task<object> SyncInventoryList(int cid, string Bdate)
    {
        var KingdeeUtil = await _kingdeeUtil.GetClient("kindeeIcloud_basicinfo_inventorylist");

        List<Inventory> InserLsit = new();
        List<Inventory> UpdateList = new();

        string filterString = $"FUseOrgId.FNumber = '{KingdeeConfigConst.ORGID}' ";
        if (!string.IsNullOrEmpty(Bdate))
            filterString += $" and FCreateDate >= '{Bdate}'";

        string FilterString = $"FUseOrgId.FNumber = '{KingdeeConfigConst.ORGID}' and FCreateDate >= '{Bdate}'";
        var list = KingdeeUtil.Query<BD_MATERIAL_Dto>(KingdeeFormConst.BD_MATERIAL, FilterString);
        if (list.Count == 0)
            return await Task.FromResult(Oops.Oh("金蝶无数据可同步！"));

        Dictionary<string, int> keyValuePairs = new()
        {
            {"CHLB01_SYS",0 },
            {"CHLB03_SYS",2 },
            {"CHLB05_SYS",1 },
            {"CHLB04_SYS",2 },
            {"CHLB02_SYS",5 }
        };
        //循环插入本地表
        foreach (var item in list)
        {
            string FCATEGORYID = item.FCategoryId_FNumber;

            Inventory obj = new Inventory()
            {
                Inventory_ID = item.FNumber,
                Description = item.F_asdg_Text1,
                SourceName = item.FName,
                Status = item.FForbidStatus == "A" ? "有效" : "冻结",
                CatID = item.FSpecification,
                RwBox = 1,
                Type = 0,
                Unit = item.FStoreUnitID__FNumber,
                Lowest_Limit = item.FMinStock,
                CreateName = item.FCreatorId,
                CreateDate = item.FCreateDate,
                //辅助单位
                CF01 = item.FAuxUnitID__FNumber,
                Is_Standard = -1,
                BatchTrace = -1,
                BatchMethod = 0,
                Trace = 1,
                Logo = string.Empty,
                _cid = cid,
            };

            if (keyValuePairs.ContainsKey(FCATEGORYID))
                obj.Type = keyValuePairs[FCATEGORYID];

            if (FCATEGORYID == "CHLB01_SYS")
                obj.Is_Standard = 0;

            //判断档案是否存在
            bool isExist = await _inventoryRepository.IsAnyAsync(x => x.Inventory_ID == obj.Inventory_ID);
            if (isExist)
            {
                UpdateList.Add(obj);
            }
            else
            {
                InserLsit.Add(obj);
            }
        }
        if (InserLsit.Count == 0 && UpdateList.Count == 0)
            throw Oops.Oh("当前同步的档案本系统中已存在！");

        try
        {
            _inventoryRepository.Context.Ado.BeginTran();

            var obj = await _inventoryRepository.AsInsertable(InserLsit).ExecuteCommandAsync();
            obj = await _inventoryRepository.AsUpdateable(UpdateList)
                .UpdateColumns(x => new
                {
                    x.Description,
                    x.Status,
                    x.Style,
                    x.CatID,
                    x.RwBox,
                    x.Type,
                    x.Unit,
                    x.Lowest_Limit,
                    x.Is_Standard,
                    x.TechnologyName,
                    x.SourceName,
                    x.CF01
                })
                .ExecuteCommandAsync();

            _inventoryRepository.Context.Ado.CommitTran();
            return InserLsit.Concat(UpdateList);
        }
        catch (Exception ex)
        {
            _inventoryRepository.Context.Ado.RollbackTran();
            throw Oops.Oh(ex.Message);
        }
    }
    #endregion
}
